package org.jetlinks.pro.things.impl.converter;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 使用映射进行消息转换,映射的source表示转换源字段,target表示转换的目标字段,
 * 字段支持表达式例如: ${value},表达式使用传入的context进行解析
 * <pre>
 *     [
 *          {"source":"${value}","target":"value"},
 *          {"source":"${value}","target":"${key}"},
 *     ]
 * </pre>
 *
 * @author zhouhao
 * @since 1.12
 */
@AllArgsConstructor
public class MappingThingMessageConverter extends ExpressionThingMessageConverter {

    private final List<Mapping> mappings;

    @Override
    protected Map<String, ?> getDefaultExpression() {
        return mappings
            .stream()
            .collect(Collectors.groupingBy(Mapping::getTarget, Collectors.mapping(Mapping::getSource, Collectors.toSet())));
    }

    @Getter
    @Setter
    public static class Mapping {
        private String source;

        private String target;
    }
}
